<?php

class Group_IndexController extends Zend_Controller_Action
{
	private $_object;

	public function init()
	{
		$this->_object = new Admin_Model_Group ();
	}

	public function indexAction()
	{
		$object_arr = ( array ) $this->_object->fetchObjects ( $this->_object->fetchGroups () );
		$paginator = Zend_Paginator::factory ( $object_arr );
		$paginator->setCurrentPageNumber ( $this->_request->getParam ( 'page' ) );
		$this->view->paginator = $paginator;
	}

	public function insertAction()
	{
		//lay tham so
		$request = $this->getRequest ();
		$adminAction = $request->getParam ( "adminAction" );
		
		//tao form
		$form = new Group_Form_Group_Insert ( $this );
		$object_arr = array (
			"" => "- Chọn -" 
		) + $this->_object->fetchOptions ( $this->_object->fetchGroups () );
		$form->getElement ( "group_parent_code" )->setMultiOptions ( $object_arr );
		
		//xu li
		if ($request->isPost ())
		{
			if ($form->isValid ( $request->getPost () ))
			{
				try
				{
					$group = new Admin_Model_Group ( $form->getValues () );
					if($this->_object->fetchRowAllBase("group_code='{$group->group_parent_code}'", null,$parent_group)!==false)
					{
						$group->group_level = $parent_group->group_level+1;
						$group->group_permission = $parent_group->group_permission;
					}
					else
					{
						$group->group_level = 0;
					}
					$group->insertBase ();
					$this->_helper->flashMessenger->addMessage ( "Thêm thành công" );
					if ($adminAction == "save-and-new")
						return $this->_helper->redirector ( 'insert', 'index', 'group', array () );
					return $this->_helper->redirector ( 'index', 'index', 'group', array () );
				}
				catch ( Exception $e )
				{
					if ($e->getCode () == 23000)
						$form->getElement ( "group_code" )->setErrors ( array (
							"value" => "Mã nhóm người dùng đã tồn tại" 
						) );
				}
			}
		}
		
		//truyen tham so cho view
		$this->view->form = $form;
	}

	public function updateAction()
	{
		//lay tham so
		$request = $this->getRequest ();
		$adminAction = $request->getParam ( "adminAction" );
		$id = $request->getParam ( "id" );
		
		//lay doi tuong can cap nhat
		$this->_object->findBase ( $id );
		
		//tao form
		$form = new Group_Form_Group_Update ( $this );
		$object_arr = array (
			"" => "- Chọn -" 
		) + $this->_object->fetchOptions ( $this->_object->fetchGroups () );
		$form->getElement ( "group_parent_code" )->setMultiOptions ( $object_arr );
		
		//xu li
		if ($request->isPost ())
		{
			if ($form->isValid ( $request->getPost () ))
			{
				$group = new Admin_Model_Group ( $form->getValues () );
				$group->updateBase ( $id );
				$this->_helper->flashMessenger->addMessage ( "Cập nhật thành công" );
				if ($adminAction == "save-and-new")
					return $this->_helper->redirector ( 'insert', 'index', 'group', array () );
				return $this->_helper->redirector ( 'index', 'index', 'group', array () );
			}
		}
		else
		{
			$form->populate ( $this->_object->toArray () );
		}
		
		//truyen tham so cho view
		$this->view->form = $form;
	}

	//xóa 1 hoặc nhiều dòng
	public function deleteAction()
	{
		$this->_helper->action->delete ( $this->_object, 'afterDelete', 'beforeDelete' );
	}

	//hàm kiểm tra dữ liệu ràng buộc trước khi xóa
	//nếu trả về true thì cho xóa, ngược lại kg cho xóa
	public function beforeDelete()
	{
		$request = Zend_Controller_Front::getInstance ()->getRequest ();
		$ids = (array)$request->getParam ( 'id');
		$msg = "";
		foreach ($ids as $id)
		{
			//lay san pham
			$group = new Admin_Model_Group();
			$group->findBase ( $id );

			//Kiem tra xem co tai khoan nao thuoc nhom nay?
			$account = new Admin_Model_Account();
			if ($account->fetchRowAllBase ( "account_group_code = '{$group->group_code}'" ) !== FALSE)
			{
				$msg .= " - Người dùng có mã số: <strong>{$account->account_username}</strong>";
				break;
			}
		}				
		if($msg!="")
		{
			$msg = "Dữ liệu này đã có trong:<br />".$msg;
			$this->_helper->flashMessenger ( $msg );
			return false;
		}
		return true;
	}

	//hàm giải phóng dữ liệu liên quan sau khi xóa
	public function afterDelete()
	{
	
	}

	/*public function assignforactionAction()
	{
		//tu dong cap nhat danh sach quyen han vap db
		$permissions = $this->autoUpdate ( 0 );
		
		//gan so thu tu
		$i = 0;
		$k = 1;
		$flag = "";
		$array_action [""] = "- Chọn -";
		foreach ( $permissions as $permission )
		{
			if ($permission->controller != $flag)
			{
				$flag = $permission->controller;
				$i = 1;
				$k ++;
			}
			$array_action [$permission->controller . "." . $permission->action] = ($k - 1) . "." . $i . " - " . $permission->getNote ();
			$i ++;
		}
		
		//truyen tham so cho view
		$this->view->id_action = $this->_request->getParam ( "id_action" );
		$this->view->list_action = $array_action;
		$this->view->contentTitle = "Phân quyền cho nhóm người dùng";
	}*/
	
	/*public function updateforactionAction()
	{
		$action = $_POST ['cboAction'];
		if ($action == "")
			die ();
		
		$array = $this->_request->getPost ( 'chk', array () );
		
		$group = new Admin_Model_Group ();
		$groups = $group->fetchAllBase ();
		foreach ( $groups as $group )
		{
			//xoa du lieu permission
			$permission = $group->getPermission ();
			
			$permission = str_replace ( "," . $action, "", $permission );
			$permission = str_replace ( $action, "", $permission );
			
			//them du lieu
			if (in_array ( $group->getId (), $array ))
			{
				if ($permission != "")
					$permission .= ",";
				$permission .= $_POST ['cboAction'];
			}
			
			//cap nhat
			$group->setPermission ( $permission );
			$group->updateBase ();
		}
		
		$this->_helper->redirector ( "assignforaction", "group", "default", array (
			"id_action" => $action 
		) );
	}*/
	
	/*public function ajaxAction()
	{
		//tao layout
		Zend_Layout::startMvc ( array (
			'layoutPath' => $this->_dirApp ['layout'], 'layout' => 'none' 
		) );
		
		//lay tham so
		$action = $this->_request->getParam ( "id_action" ); //ten quyen. vi du: TruckEscortChargeController.indexAction		
		$action = $this->_request->getParam ( "id_action" ); //ten quyen. vi du: TruckEscortChargeController.indexAction
		

		// action body
		$group = new Admin_Model_Group ();
		
		if ($action != "")
			$this->view->strHTML = $group->listRecursive ( "", "", "<img src='" . $this->view->dirApp ["image"] . "xuonghang.png'/>&nbsp;", $action );
	}*/

	//cấp quỳen cho nhóm người dùng
	public function assignAction()
	{
		//nhan tham so
		$id = $this->_request->getParam ( 'id' );
		$group_permission = $this->_request->getParam ( 'group_permission', array () );
		$adminAction = $this->_request->getParam ( 'adminAction', '' );
		
		//lay danh sach cac quyen cua nhom 
		$this->_object->findBase ( $id );
		
		//xu li
		if ($adminAction != "") //neu post gia tri
		{
			$group_permission = "," . implode ( ",", $group_permission ) . ",";
			$group = new Admin_Model_Group ();
			$group->group_permission = $group_permission;
			$group->updateBase ( $id );
			$this->_helper->flashMessenger->addMessage ( "Phân quyền thành công" );
			if ($adminAction == "apply")
				$this->_helper->redirector ( "assign", "index", "group", array (
					"id" => $id 
				) );
			else
				$this->_helper->redirector ( "index" , "index", "group",array());
		}
		else //lần đầu tiên vào
		{
			//dong bo tinh nang cua chuong trinh voi tinh nang luu trong csdl
			$resources = $this->_helper->action->getActionList ();
			
			//kiểm tra nếu có quyền thì check vào
			$group_permission = $this->_object->group_permission;
			foreach ( $resources as $module_name => $value )
			{
				foreach ( $value ['controllers'] as $controller_name => $value2 )
				{
					foreach ( $value2 ['actions'] as $action_name => $value3 )
					{
						$tmp = "";
						if (strpos ( $group_permission, ",".$value3 ['action_url']."," ) !== false)
							$tmp = " checked='checked' ";
						$resources [$module_name] ['controllers'] [$controller_name] ['actions'] [$action_name] ['checked'] = $tmp;
					}
				}
			}
		}
		
		//truyen cho view
		$this->view->resources = $resources;
	}

	public function ajaxUpdateNoteAction()
	{
		//bỏ layout
		$this->_helper->layout ()->disableLayout ();
		$this->_helper->viewRenderer->setNoRender ( true );
		
		//lay tham so
		$target = $this->_request->getParam ( 'target', '' );
		$note = $this->_request->getParam ( 'note', '' );
		
		//cap nhat		
		list ( $type, $id ) = split ( "_", $target );
		switch ($type)
		{
			case "action" :
				$object = new Admin_Model_Action ();
				break;
			case "controller" :
				$object = new Admin_Model_Controller ();
				break;
			case "module" :
				$object = new Admin_Model_Module();
				break;
		}
		$column = $type . "_note";
		$object->$column = $note;
		$object->updateBase ( $id );
	}
}